//
//  LYCustomAlertView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/25.
//

import UIKit
import SnapKit

class LYCustomAlertView: UIView {
    
    // MARK: - UI Elements
    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.layer.cornerRadius = 12
        view.layer.masksToBounds = true
        return view
    }()
    
    private lazy var backgroundImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.image = UIImage(named: "alert_bg_image")
        return iv
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 18)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.textColor = UIColor(hex: "#000000")
        label.textAlignment = .left
        return label
    }()
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.textColor = UIColor(hex: "#000000")
        return label
    }()
    
    private lazy var buttonStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.distribution = .fillEqually
        stack.spacing = 10
        return stack
    }()
    
    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "alert_close"), for: .normal)
        button.addTarget(self, action: #selector(clickCloseButton(_:)), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Properties
    private var buttons: [UIButton] = []
    private var buttonActions: [() -> Void] = []
    private var isVisible = false
    private var completionHandlers: [() -> Void] = []
    
    var isShowingAlert: Bool {
        return isVisible
    }

    // MARK: - Initialization
    init(title: String? = nil,
         message: String? = nil,
         backgroundImage: UIImage? = nil) {
        super.init(frame: UIScreen.main.bounds)
        setupUI()
        configureContent(title: title, message: message, backgroundImage: backgroundImage)
    }
    
    init(view: UIView,
         backgroundImage: UIImage? = nil) {
        super.init(frame: UIScreen.main.bounds)
        setupViewUI(view: view,
                    backgroundImage: backgroundImage)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        addSubview(containerView)
        addSubview(closeButton)
        backgroundImageView.isUserInteractionEnabled = true
        containerView.addSubview(backgroundImageView)
        backgroundImageView.addSubview(titleLabel)
        backgroundImageView.addSubview(messageLabel)
        backgroundImageView.addSubview(buttonStackView)

        containerView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.9)
        }
        
        closeButton.snp.makeConstraints { make in
            make.centerX.equalTo(containerView)
            make.top.equalTo(containerView.snp.bottom).offset(20)
        }
        
        backgroundImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(35)
            make.leading.trailing.equalToSuperview().inset(20)
        }
        
        messageLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(20)
        }
        
        buttonStackView.snp.makeConstraints { make in
            make.top.equalTo(messageLabel.snp.bottom).offset(20)
            make.leading.trailing.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().offset(-20)
            make.height.equalTo(44)
        }
    }
    
    // MARK: - UI Setup
    private func setupViewUI(view: UIView,
                             backgroundImage: UIImage? = nil) {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        addSubview(containerView)
        addSubview(closeButton)
        backgroundImageView.image = backgroundImage
        backgroundImageView.isUserInteractionEnabled = true
        containerView.addSubview(backgroundImageView)
        backgroundImageView.addSubview(view)
        backgroundImageView.addSubview(titleLabel)
        backgroundImageView.addSubview(buttonStackView)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(55)
            make.leading.trailing.equalToSuperview().inset(20)
        }

        containerView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.9)
        }
        
        closeButton.snp.makeConstraints { make in
            make.centerX.equalTo(containerView)
            make.top.equalTo(containerView.snp.bottom).offset(20)
        }
        
        if let backgroundImage = backgroundImage,
           backgroundImage.size.height > 0,
           backgroundImage.size.width > 0 {

            let aspectRate = backgroundImage.size.width / backgroundImage.size.height
            let margin = 20.0
            let width = SCREEN_WIDTH - margin * 2.0
            let height = width / aspectRate

            backgroundImageView.snp.makeConstraints { make in
                make.centerX.top.equalToSuperview()
                make.width.equalTo(width)
                make.height.equalTo(height)
                make.bottom.equalToSuperview()
            }
            
        } else {
            backgroundImageView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    // MARK: - Public Methods
    func addButton(_ button: UIButton, action: @escaping () -> Void) {
        let buttonIndex = buttons.count
        buttons.append(button)
        
        // 使用weak self确保不会造成循环引用
        buttonActions.append({ [weak self] in
            guard let self = self else { return }
            if self.isVisible {
                action()
            }
        })
        
        button.tag = buttonIndex
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        buttonStackView.addArrangedSubview(button)
    }
    
    func show(in view: UIView? = nil, completion: (() -> Void)? = nil) {
        guard let targetView = view ?? UIApplication.shared.currentKeyWindow else { return }
        guard !isVisible else { return }
        
        isVisible = true
        alpha = 0
        targetView.addSubview(self)
        
        self.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
        containerView.alpha = 0
        
        UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
            self.alpha = 1
            self.containerView.transform = .identity
            self.containerView.alpha = 1
        }) { _ in
            completion?()
        }
    }
    
    func hide(completion: (() -> Void)? = nil) {
        guard isVisible else { return }
        isVisible = false
        
        UIView.animate(withDuration: 0.2, animations: {
            self.containerView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
            self.containerView.alpha = 0
            self.alpha = 0
        }) { [weak self] _ in
            guard let self = self else { return }
            self.removeFromSuperview()
            completion?()
        }
    }
    
    // MARK: - Private Methods
    @objc private func buttonTapped(_ sender: UIButton) {
        let index = sender.tag
        guard index < buttonActions.count else { return }
        
        // 执行存储的action闭包
        buttonActions[index]()
//        hide()
    }
    
    @objc func clickCloseButton(_ sender: UIButton) {
        hide()
    }
    
    private func configureContent(title: String?, message: String?, backgroundImage: UIImage?) {
        titleLabel.text = title
        messageLabel.text = message
        if let backgroundImage = backgroundImage {
            
            backgroundImageView.image = backgroundImage
        }
    }
}
